<?php

declare(strict_types=1);

namespace app\middleware;

use app\common\model\AdminUser;
use app\common\service\AdminToken;
use app\traits\Jump;
use think\facade\Cookie;

/**
 * 验证管理员是否登录中间件
 * Class CheckToken
 * @package app\middleware
 */
class CheckAdminLogin
{
    use Jump;
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $tenantId = intval(TENANTID);
        $tenantId = $tenantId ? $tenantId : config('app.default_tenantid');
        if (!isset($tenantId)) {
             $this->error('租户id丢失!', '/admin/login?error=2');
        }

        $adminToken = Cookie::get('admin_token');
        if (!$adminToken) {
            $this->error('请先登录', '/admin/login?error=3',401);
        }

        $admintokenService = new AdminToken();
        $value = $admintokenService->getValue($adminToken);
        if (!$value) {
           $this->error('登录失效', '/admin/login?error=1',401);
           return $next($request);
        }
        $adminUser = new AdminUser();
        $adminInfo = $adminUser->find(intval($value['uid']));
        if($adminInfo['status'] <=0){
           $this->error('用户状态不可用');
        }
        //刷新活动时间
        $adminInfo->save(['activity_at'=>date('Y-m-d H:i:s')]);
        //刷新token过期时间
        $admintokenService->refreshExpire($adminToken);
        $request->adminTokenValue = $value;
        $request->tenantId = $tenantId;

        //权限验证
        $uri = strtolower('/admin/' . $request->controller() . '/' . $request->action());
        $request->adminUri =  $uri;
        $rules = getRuleList($value['uid']);
        //echo $uri; print_r($rules);exit();
        if (!in_array('*', $rules) && !in_array($uri, $rules)) {
              $this->error('无权限访问');
        }


        return $next($request);
    }
}
